<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DecisionMaking.BusinessLogic.Model.RunSimulationModel>" MasterPageFile="~/Views/Shared/Site.Master" %>
<asp:Content runat="server" ID="Content1" ContentPlaceHolderID="TitleContent">Run Simulation</asp:Content>

<asp:Content runat="server" ID="Content3" ContentPlaceHolderID="MainContent">
 <%= Html.ValidationSummary("Candidate creation was unsuccessful. Please correct the errors and try again.") %>

    <% using (Ajax.BeginForm("Run", "Simulation", new AjaxOptions {OnSuccess = "onSimulationStart"}))
       {%>
        <div>
        	<%=Html.HiddenFor(m => m.EnvironmentId)%>

            <p>
                <%=Html.LabelFor(m => m.DefinitionId)%>
                <%=Html.DropDownListFor(m => m.DefinitionId, new SelectList(Model.AlgorithmDefinitions, "Id", "Name"))%>
                <%=Html.ValidationMessageFor(m => m.DefinitionId)%>
            </p>                      
            <p>
                <input type="submit" value="Run Simulation" />
            </p>               
        </div>
    <% } %>    
    <div id="progressbar"></div>
    <div id="errorMessage" class="field-validation-error"></div>
    <script type="text/javascript">
        var _simulationId;
        var _handle;

        $(document).ready(function () {
            $('#progressbar').progressbar();
        });

        function onSimulationStart(context) {
            var json = context.get_data();
            var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

            _simulationId = data.simulationId;

            _handle = window.setInterval(poll, 2000);
        }

        function poll() {
            $.getJSON('<%= Url.Action("PollProgress", "Simulation") %>', { simulationId: _simulationId }, function (data) {
                $('#progressbar').progressbar({ value: data.done * 100 });

                if (!data) { // HTTP error or otherwise bad result
                    window.clearInterval(_handle);
                    $('#errorMessage').html('Error polling server; got: ' + data);
                }
                else if (data.errorMessage) {
                    // error occured, display it and stop polling
                    window.clearInterval(_handle);
                    $('#errorMessage').html(data.errorMessage);
                }
                else if (data.done == 1) {
                    window.clearInterval(_handle);
                    document.location = '<%= Url.Action("Index", "Reports") %>';
                }
            });
        }

    </script>
</asp:Content>
